import router from './router'
import store from './store'
import request from '@/utils/request'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // 判断请求的URL是否含有index及loginname及dbid及access_token
  var url = to.fullPath
  if(url.indexOf('loginname')!=-1&&url.indexOf('storeNumber')!=-1&&url.indexOf('storeName')!=-1) {
    // console.log(url)

    // set token
    let token = 'admin-token'
    // commit('SET_TOKEN', token)
    setToken(token)

    // get path param
    // url example:/index.html?loginname=stephen007&dbid=79579303963750&access_token=123
    let loginname = to.query.loginname
    if (loginname.substring(0,1) == "u") {
      loginname = loginname.substr(1)
    }

    // console.log(loginname)
    // let dbid = to.query.dbid
    // let accessToken = to.query.access_token
    let companyName = to.query.companyName
    let storeNumber = to.query.storeNumber
    let storeName = to.query.storeName

    let client_id = 209163
    let client_secret = "048f001b91ff1887667e64f3e156d610"
    // console.log("loginname=" + loginname + ", dbid=" + dbid + ", accessToken=" + accessToken)

    // set session data
    let password = 'jdy888888'
    sessionStorage.setItem("login_name", JSON.stringify(loginname))
    sessionStorage.setItem("password", JSON.stringify(password))
    sessionStorage.setItem("companyName", JSON.stringify(companyName))
    // sessionStorage.setItem("storeNumber", JSON.stringify(storeNumber))
    // sessionStorage.setItem("storeName", JSON.stringify(storeName))
    sessionStorage.setItem("client_id", JSON.stringify(client_id))
    sessionStorage.setItem("client_secret", JSON.stringify(client_secret))

    // 测试数据
    // let storeId = "12345678912"
    // let storeLocation = '哈工大';
    // let repositoryNumber = 'QE254617';

    // get storeLocation and store repository number
    await request.post('/api/v1/linkjdy/getdbIdAndToken/' + loginname + "/" 
    + password + "/" + client_id + "/" + client_secret + "/" + storeNumber).then(response=>{
      var respData = response.data
      let storeId = respData.storeId
      let storeLocation = respData.location
      let repositoryNumber = respData.data.number

      // set store data to session
      let store = {
        storeNumber: storeNumber,
        storeId: storeId,
        storeName: storeName,
        storeLocation: storeLocation,
        repositoryNumber: repositoryNumber
      }
      sessionStorage.setItem("store", JSON.stringify(store));

      // set account data
      let dbid = respData.dbid
      let accessToken = respData.access_token
      sessionStorage.setItem("dbid", JSON.stringify(dbid))
      sessionStorage.setItem("access_token", JSON.stringify(accessToken))

    }).catch(()=>{
      console.log('获取账户与门店数据出错，请联系管理员！')
      return
    })

    // index = true
    // next({ path: '/index' })
  }

  // determine whether the user has logged in
  const hasToken = getToken()

  console.log(from)
  console.log(to)
  console.log('---------------------------')

  if (hasToken) {
    // console.log('hastoken')
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next()
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
          // console.log('hasRoles')
          // console.log(store.getters.roles)
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          // console.log(roles)
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // console.log('add routes')
          // console.log(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
          // console.log('finished!')
        } catch (error) {
          // remove token and go to login page to re-login
          // console.log('add route wrong!')
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          // console.log(error)
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // console.log('hasnotoken')
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      // console.log('redirect to login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
